<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Requests\TradeQueueRequest;
use App\Models\Asset;
use App\Models\TradeQueue;
use App\Transformers\TradeQueueTransformer;
use Dingo\Api\Exception\ResourceException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class TradeQueueController extends Controller
{
    public function index(Request $request)
    {
        $user = auth('api')->user();

        $perPage = $request->input('per_page',20);
        $order = $request->input('order','desc');
        $startTime = $request->input('start_time','0');
        $endTime = $request->input('end_time',time());

        $res = $user->tradeQueues()->whereBetween('created_at', [$startTime, $endTime])->where('type',\request('type'))->orderBy('id',$order)->paginate($perPage);
        return $this->response->paginator($res,new TradeQueueTransformer());
    }
    
    //
    public function store(TradeQueueRequest $request)
    {

        $user = auth('api')->user();
        if(!$user->wechat) {
            throw new ResourceException('error',[['error_code'=>'430004','message'=>'请先完善个人信息！']]);
        }
        $dataArr = $request->only(['amount','type']);
        $dataArr['user_id'] = $user->id;
        $dataArr['unmatch_amount'] = $dataArr['amount'];//$type == 'deposit' ? 0 : $dataArr['amount'];

        // todo 没有判断可用余额是否够下提现的单子

//        $isTradeQueue = $this->moreTime($dataArr['type'],$dataArr['amount']);

        $res = TradeQueue::create($dataArr);
        return $res;
    }

    // 因为结算那一刻起 开始算24小时的（validate）
    public function moreTime($type,$amount)
    {
        $nowTime = strtotime(date('Y-m-d H:i:s'));
        $user = auth('api')->user();
        $tradeQueue = new TradeQueue();
        switch ($type) {
            case 'deposit':
                return $tradeQueue->deposit($type,$amount,$nowTime,$user);
            case 'withdraw':
                $type = 'deposit';
                return $tradeQueue->withdraw($type,$amount,$nowTime,$user);
            default:
                return false; // 不会出现
        }
    }

}
